<script setup>
import { ref } from "vue";
import { useHistoryStore } from "@/stores/index.js";
import { useRouter } from "vue-router";

const historyStore = useHistoryStore();
const router = useRouter();
const search = ref("");

const delAll = () => {
  historyStore.delAll();
};
const goSearch = (item) => {
  search.value = "";
  const index = historyStore.historyList.indexOf(item);
  if (index === -1) {
    //找不到情况
    historyStore.addHistory(item);
  } else {
    //找到情况
    historyStore.delHistory(index);
    historyStore.addHistory(item);
  }
  router.push({
    path: "/searchlist",
    query: { search: item },
  });
};
</script>

<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.back()" />

    <van-search
      clearable
      placeholder="请输入搜索关键词"
      show-action
      v-model="search"
    >
      <template #action>
        <van-button type="primary" class="button" @click="goSearch(search)"
          >搜索</van-button
        >
      </template>
    </van-search>

    <div class="search-history">
      <div class="title">
        <span>最近搜索</span>
        <i class="iconfont icon-lajitong" @click="delAll"></i>
      </div>
      <div class="list">
        <div
          v-for="item in historyStore.historyList"
          :key="item"
          class="list-item"
          @click="goSearch(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.button {
  height: 34px !important;
  display: block;
}
.search {
  .search-history {
    margin-top: 10px;
    padding: 0 10px;
    .title {
      display: flex;
      justify-content: space-between;
    }
    .list {
      display: flex;
      margin-top: 20px;
      flex-wrap: wrap;
      gap: 5%;
      .list-item {
        width: 30%;
        border-radius: 10px;
        margin-bottom: 13px;
        text-align: center;
        border: 1px solid #9f9f9f;
        padding: 4px 0;
        line-height: 24px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
